package com.tom.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

@Controller
@RequestMapping("/file")
public class FileController {
    @PostMapping("/upload")
    @ResponseBody
    public String fileupload(@RequestParam(required = false) MultipartFile file, HttpServletRequest request) {
        if (file != null) {
            try {
                String filePath = "file/" + file.getOriginalFilename();
                String realPath = request.getServletContext().getRealPath(filePath);
                file.transferTo(new File(realPath));

                StringBuffer url = request.getRequestURL();
                String fileUrl = url.delete(url.length() - request.getRequestURI().length(), url.length())
                        .append(request.getContextPath())
                        .append("/" + filePath).toString();
                return "文件地址是:" + fileUrl;
            } catch (IOException e) {
                System.out.println("保存失败:" + e.getMessage());
            }
        }
        return "保存失败";
    }
}
